package com.sam.im.heiqun.uis.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.FriendAdpter;
import com.sam.im.heiqun.uis.adapters.FriendGroupAdpter;
import com.sam.im.heiqun.uis.dialogs.ItemSelectorDialog;
import com.sam.im.heiqun.uis.widgets.sidebar.CharacterParserUtil;
import com.sam.im.heiqun.uis.widgets.sidebar.CountryComparator;
import com.sam.im.heiqun.uis.widgets.sidebar.CountrySortModel;
import com.sam.im.heiqun.uis.widgets.sidebar.GetCountryNameSort;
import com.sam.im.heiqun.uis.widgets.sidebar.SideBar;
import com.sam.im.heiqun.utils.ArrayUtil;
import com.sam.im.heiqun.utils.DateFormatUtil;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.log.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Cancellable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 *
 */
public class GroupUsersActivity extends BaseSwipeBackActivity implements FriendGroupAdpter.FriendListClickListener, SwipeRefreshLayout.OnRefreshListener, TextWatcher {

    private static final String TAG = GroupUsersActivity.class.getSimpleName();
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.list_friend)
    RecyclerView list_friend;
    @BindView(R.id.friend_dialog)
    TextView friend_dialog;
    @BindView(R.id.friend_sidebar)
    SideBar friend_sidebar;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;
    @BindView(R.id.search_edit)
    EditText search_edit;
    @BindView(R.id.relative_noresult)
    LinearLayout relattive_noresult;
    @BindView(R.id.tv_content)
    TextView tvcontent;
    PGService mPgService;
    String uid = "";
    private int type = 0;//判断是否是创建群组使用，0-是；1-不是;;2-选择群成员

    private List<CountrySortModel> mFriends = new ArrayList<>();

    private CountryComparator pinyinComparator;
    /**
     * 获取字符串缩写
     */
    private CharacterParserUtil characterParserUtil;
    /**
     * 获取首字母
     */
    private GetCountryNameSort countryChangeUtil;
    private FriendGroupAdpter mAdapter;
    private String groupId;
    private int role;
    private int lastVisibleItem = 0;
   private LinearLayoutManager mLayoutManager;
    private PGService mPGservice;
    private int groupmanageNum = 0;


    @Override
    protected String getTitleText() {
        return getString(R.string.group_details_title);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_selecte_groupfriend;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);
        type = getIntent().getIntExtra("type", 0);
        ok.setVisibility(View.GONE);
        mPgService = PGService.getInstance();

        groupId = getIntent().getStringExtra("groupId");
        role = getIntent().getIntExtra("role", 0);
        initView();

    }

    //
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateList(EventBusTypeData event) {
        if (null != event) {
            switch (event.getType()) {
                case EventBusType.GROUP_APPLY_GRPOUP_OUT:
                    if (event.getMsg().equals("" + groupId)) {
                        showToast("您已被踢出群组！");
                        finish();
                    }
                    break;
                case EventBusType.GROUP_APPLY_GRPOUP_OUT_OTH:
                    initData();
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refrenshUser(Integer code) {
        if (null != code) {
            if (code == EventBusType.GROUP_ADD_USER) {
                try {
                    getGroupMember(groupId, ToolsUtils.getMyUserId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initView() {

        mPGservice = PGService.getInstance();

        List<GroupFriendEntivity> groupFriendEntivities2 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{groupId, "2"}));
        if (null != groupFriendEntivities2 && groupFriendEntivities2.size() > 0) {
            groupmanageNum = groupFriendEntivities2.size();
        }

        /** 右侧字母栏*/
        friend_sidebar.setVisibility(View.GONE);
        friend_sidebar.setTextView(friend_dialog);
        pinyinComparator = new CountryComparator();
        countryChangeUtil = new GetCountryNameSort();
        characterParserUtil = new CharacterParserUtil();
        search_edit.addTextChangedListener(this);
        // 右侧sideBar监听
        /*friend_sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    //这个设置的方式不是很准确流畅
                    list_friend.getLayoutManager().scrollToPosition(position);
                }
            }
        });*/
        /** 右侧字母栏 */
        mLayoutManager = new LinearLayoutManager(getApplicationContext());
        list_friend.setLayoutManager(mLayoutManager);
        mFriends = new ArrayList<>();
        mAdapter = new FriendGroupAdpter(getApplicationContext(), mFriends);
        mAdapter.setItemClickListener(this);
        mAdapter.setOnLongClickListener(new FriendGroupAdpter.OnLongClickListener() {
            @Override
            public boolean OnLongClick(final int pos) {

                final Long id = mFriends.get(pos).getId();
                int fdrole = ToolsUtils.getGroupRole(groupId, "" + id);
                if (1 == fdrole) return false;
                ItemSelectorDialog.Entity[] items = new ItemSelectorDialog.Entity[0];
                if (1 == role) {//群主有所有权限
                    items = new ItemSelectorDialog.Entity[3];
                    if (2 == fdrole) {
                        items[0] = new ItemSelectorDialog.Entity(getResources().getString(R.string.calen_gly));//取消管理员
                    } else {
                        items[0] = new ItemSelectorDialog.Entity(getResources().getString(R.string.set_gly));//设置管理员
                    }
                    items[1] = new ItemSelectorDialog.Entity(getResources().getString(R.string.delete_group_user));//删除群成员

                    items[2] = new ItemSelectorDialog.Entity(getResources().getString(R.string.group_no_spike));//禁言群成员

                } else if (2 == role) {//管理员不能踢管理员
                    if (1 != fdrole && 2 != fdrole) {
                        items = new ItemSelectorDialog.Entity[2];
//                        items[0] = getResources().getString(R.string.set_gly);//设置管理员
                        items[0] = new ItemSelectorDialog.Entity(getResources().getString(R.string.delete_group_user));//删除群成员
                        items[1] = new ItemSelectorDialog.Entity(getResources().getString(R.string.group_no_spike));//禁言群成员
                    }

                } else {//普通群成员不能踢人
                    return false;
                }

                final ItemSelectorDialog<ItemSelectorDialog.Entity> itemSelectorDialog = new ItemSelectorDialog<>(GroupUsersActivity.this);
                itemSelectorDialog.setTitle(null);
                itemSelectorDialog.setItems(items);
                itemSelectorDialog.setDialogClickListener(new ItemSelectorDialog.DialogItemClickListener<ItemSelectorDialog.Entity>() {
                    @Override
                    public void confirm(int position, ItemSelectorDialog.Entity result) {
                        if (getResources().getString(R.string.calen_gly).equals(result.getText())) {
                            if (1 == role) setGroupAdmin("" + mFriends.get(pos).getId(), "2");
                        } else if (getResources().getString(R.string.set_gly).equals(result.getText())) {
                            if (groupmanageNum >= 5) {
                                showToast("群管理员个数不得超过5个");
                            } else {
                                if (1 == role) setGroupAdmin("" + mFriends.get(pos).getId(), "1");
                            }
                        } else if (getResources().getString(R.string.delete_group_user).equals(result.getText())) {
                            if (1 == role || 2 == role)
                                removeGroupMember("" + mFriends.get(pos).getId());
                        } else if (getResources().getString(R.string.group_no_spike).equals(result.getText())) {
                            String[] times = new String[]{getResources().getString(R.string.nospick_time_1), getString(R.string.nospick_time_2)
                                    , getString(R.string.nospick_time_3), getString(R.string.nospick_time_4)};
                            MyDialog.ShowDialog(GroupUsersActivity.this, "", times, new MyDialog.DialogItemClickListener() {
                                @Override
                                public void confirm(String result) {
                                    String time = "";
                                    if (getResources().getString(R.string.nospick_time_1).equals(result)) {
                                        time = "" + (60 * 10);
                                    } else if (getResources().getString(R.string.nospick_time_2).equals(result)) {
                                        time = "" + (60 * 60);
                                    } else if (getResources().getString(R.string.nospick_time_3).equals(result)) {
                                        time = "" + (60 * 60 * 24);
                                    } else if (getResources().getString(R.string.nospick_time_4).equals(result)) {
                                        time = "" + (60 * 60 * 24 * 7);
                                    }
                                    if (1 == role || 2 == role)
                                        updateGroupMember("" + mFriends.get(pos).getId(), time);
                                }
                            }).show();
                        }
                    }
                });

                final TextView view = itemSelectorDialog.findItemViewWithText(getResources().getString(R.string.group_no_spike));
                if (view != null) {

                    final long lastAnExcuseTime = ToolsUtils.getLastAnExcuseTime(groupId, String.valueOf(id));
                    view.setEnabled(lastAnExcuseTime <= 0);
                    if (lastAnExcuseTime > 0) {

                        final long count = lastAnExcuseTime / 1000;
                        Observable.interval(0, 1, TimeUnit.SECONDS)
                                .take(count)
                                .map(new Function<Long, String>() {
                                    @Override
                                    public String apply(Long aLong) throws Exception {

                                        if (aLong == count - 1) {
                                            return "禁言";
                                        }
                                        return "禁言（" + DateFormatUtil.transferLastTime(ToolsUtils.getLastAnExcuseTime(groupId, String.valueOf(id))) + ")";
                                    }
                                })
                                .compose(RxJavaUtil.<String>bindDialogDismissLifeCycle(itemSelectorDialog))
                                .compose(RxJavaUtil.<String>applySchedules())
                                .subscribe(new AbsAPICallback<String>() {
                                    @Override
                                    public void onNext(String s) {
                                        view.setText(s);
                                    }

                                    @Override
                                    protected void onResultError(ApiException ex) {

                                    }
                                });

                    }
                }
                itemSelectorDialog.show();
                return true;
            }
        });
        mAdapter.setHintHeadview(true);
        list_friend.setAdapter(mAdapter);
        list_friend.addItemDecoration(new DividerItemDecorationUtils(getApplicationContext(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        initData();
        search_edit.setOnKeyListener(onKeyListener);
        swipeRefreshWidget.setOnRefreshListener(this);

        // 这句话是为了，第一次进入页面的时候显示加载进度条
        swipeRefreshWidget.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));

        list_friend.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == mAdapter.getItemCount()) {
                    swipeRefreshWidget.setRefreshing(true);
                    // 此处在现实项目中，请换成网络请求数据代码，sendRequest .....
                    List<ImFriendEntivity> temps = ToolsUtils.getGroupUserS(groupId, mFriends.size());
                    showListUser(temps);
                    swipeRefreshWidget.setRefreshing(false);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }

        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateList(Integer event) {
        if (event == EventBusType.GROUP_APPLY_GRPOUP_LEVEL_N) {
            // tvAite.setVisibility(View.GONE);
            try {

            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }

    /**
     * 审核群成员/更新群成员禁言状态 /chat/updateGroupMember
     * destId 群成员id number @mock=17228
     * groupId 群组id number @mock=2643
     * ope  number @mock=0 时间
     * type  number @mock=1
     * userId  number @mock=17234
     */
    private void updateGroupMember(final String friendid, final String ope) {
        //删除申请实体
        showProgress(getResources().getString(R.string.commiting));

        if (null == groupId || TextUtils.isEmpty(groupId)) {
            hideProgress();
            return;
        }
        mPGservice.updateGroupMember(friendid, groupId, ope, "2", ToolsUtils.getMyUserId())
                .flatMap(new Function<ValidateEntivity, ObservableSource<SearchUserEntity>>() {
                    @Override
                    public ObservableSource<SearchUserEntity> apply(ValidateEntivity validateEntivity) throws Exception {

                        return PGService.getInstance().getGroupMember(groupId, friendid);
                    }
                })
                .doOnNext(new Consumer<SearchUserEntity>() {
                    @Override
                    public void accept(SearchUserEntity searchUserEntity) throws Exception {
                        List<ImFriendEntivity> info = searchUserEntity.getInfo();
                        ToolsUtils.saveGroupUserS(info, Long.valueOf(groupId));
                    }
                })
                .subscribe(new AbsAPICallback<SearchUserEntity>() {
                    @Override
                    protected void onResultError(ApiException ex) {
                        showToast(getResources().getString(R.string.caozuo_fail));
                        hideProgress();
                    }

                    @Override
                    public void onNext(SearchUserEntity entivity) {

//                if ("0".equals(ope)){//拒绝
                        showToast("设置成功！");
//                }else {
//                    showToast("同意成功！");
//                }
//                scrollToFinishActivity();
                        hideProgress();
                    }
                });
    }


    /**
     * 设置群管理员 chat/setGroupAdmin
     *
     * @param destId
     * @param isSet  1 为设置  其他都是取消
     * @ groupId          id
     * @ userId          请求人id
     */
    private void setGroupAdmin(final String destId, final String isSet) {
//        Log.i(TAG, "setGroupAdmin: ===================groupid="+groupid);
//        Log.i(TAG, "setGroupAdmin: ===================destId="+destId);
        mPGservice.setGroupAdmin(ToolsUtils.getMyUserId(), "" + groupId, destId, isSet)
                .flatMap(new Function<ValidateEntivity, ObservableSource<SearchUserEntity>>() {
                    @Override
                    public ObservableSource<SearchUserEntity> apply(ValidateEntivity validateEntivity) throws Exception {

                        return PGService.getInstance().getGroupMember(groupId, destId);
                    }
                })
                .doOnNext(new Consumer<SearchUserEntity>() {
                    @Override
                    public void accept(SearchUserEntity searchUserEntity) throws Exception {
                        List<ImFriendEntivity> info = searchUserEntity.getInfo();
                        ToolsUtils.saveGroupUserS(info, Long.valueOf(groupId));
                    }
                })
                .subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(SearchUserEntity friendEntivity) {//
                showToast(getResources().getString(R.string.set_success));
                initData();
                if (isSet.equals("1")) groupmanageNum++;
                else groupmanageNum--;
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 删除群成员 chat/removeGroupMember
     * destId 被删除的成员id number 17265
     * groupId 群组id number 62
     * userId 群主id或者群管理id number 17229
     */
    private void removeGroupMember(final String destId) {
        mPGservice.removeGroupMember(destId, groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {//
                showToast(getResources().getString(R.string.caozuo_success));
                Log.i(TAG, "onNext: ====================");
                List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", new String[]{groupId, destId});
                Log.i(TAG, "onNext: ====================");
                if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                    GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(0);
                    groupFriendEntivity.delete();
                }
                EventBus.getDefault().post(EventBusType.GROUP_MANAGER_GRPOUP_REFRENSH);
//                int i = 0 ;
//                if (null==mFriends &&mFriends.size()<0)return;
//                for (CountrySortModel mCountrySortModel:mFriends
//                     ) {
//                    if ((""+mCountrySortModel.getUserId()).equals(destId)){
//                        mFriends.remove(i);
//                        mAdapter.notifyDataSetChanged();
//                    }
//                    i++;
//                }
                int fdrole = ToolsUtils.getGroupRole(groupId, destId);
                if (2 == fdrole) {
                    groupmanageNum--;
                }

                mFriends.clear();
                showProgress(getResources().getString(R.string.now_down));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<ImFriendEntivity> groupUserSss = ToolsUtils.getAllGroupUeaer(groupId);

                        EventBus.getDefault().post(groupUserSss);
                    }
                }).start();
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    private void initData() {
        if (null == mFriends) mFriends = new ArrayList<>();

        Collections.sort(mFriends, pinyinComparator);//根据首字母进行排序
        mAdapter.refresh(mFriends);
        //先从本地查找
        // showProgress("正在拉取成员列表");
        showProgress(getResources().getString(R.string.now_down));
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ImFriendEntivity> groupUserSss = ToolsUtils.getAllGroupUeaer(groupId);

                EventBus.getDefault().post(groupUserSss);
            }
        }).start();
        // List<ImFriendEntivity> allGroupUeaer = ToolsUtils.getAllGroupUeaer(groupId);
        // List<ImFriendEntivity> temps = ToolsUtils.getGroupUserS(groupId, mFriends.size());
        // hideProgress();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getGroupmembers(List<ImFriendEntivity> imFriendEntivities) {
        showListUser(imFriendEntivities);
        if (imFriendEntivities.size() == 0) {//表示查询群
            getGroupMember(groupId, ToolsUtils.getMyUserId());
        }
        hideProgress();
    }

    /**
     * 查询群组好友列表
     */
    private void getGroupMember(String groupId, String fromid) {
        showProgress(getResources().getString(R.string.now_down));
        mPgService.getGroupMember(groupId, fromid).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(SearchUserEntity friendEntivity) {
                List<ImFriendEntivity> temps = ToolsUtils.gUserRemoval(friendEntivity.getInfo());

                showListUser(temps);
                hideProgress();
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    public void onAgreeNewFriendClick(View view, int position) {
        if (2 == type) {
            Intent intent = new Intent();
            intent.putExtra("id", "" + mFriends.get(position - 1).getId());
            setResult(RESULT_OK, intent);
            finish();
        } else {
            Bundle bundle = new Bundle();
            bundle.putLong("id", mFriends.get(position - 1).getId());
            bundle.putInt("type", 0);
            startActivity(FriendDetailActivity.class, bundle);
        }
    }

    @OnClick({R.id.ok, R.id.pre_v_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.ok:

                break;
        }
    }

    private void showListUser(List<ImFriendEntivity> imFriendEntivities) {
        hideProgress();
        LogUtils.d("查询到的好友列表:"+ Arrays.asList(imFriendEntivities));

        for (int i = 0; i < imFriendEntivities.size(); i++) {
            mFriends.add(ToolsUtils.changeFriendEntvity(imFriendEntivities.get(i), characterParserUtil, countryChangeUtil));
        }
      //mFriends = ToolsUtils.gCountrySortModelRemoval(mFriends);


        Collections.sort(mFriends, new Comparator<ImFriendEntivity>() {

            @Override
            public int compare(ImFriendEntivity o1, ImFriendEntivity o2) {
                LogUtils.d("查询到的好友列表排序后1:"+Long.parseLong(o1.getCreateTime() ));
                LogUtils.d("查询到的好友列表排序后2:"+Long.parseLong(o2.getCreateTime() ));
                // 进行升序排列
                if (Long.parseLong(o1.getCreateTime() )>Long.parseLong(o2.getCreateTime() ) ) {

                    return 1;
                }
                if (Long.parseLong(o1.getCreateTime() ) == Long.parseLong(o2.getCreateTime() )) {
                    return 0;
                }
                return -1;
            }
        });
        LogUtils.d("查询到的好友列表排序后:"+ Arrays.asList(mFriends));

     //   1545102460064
      //  1545102460123






        mAdapter.refresh(mFriends);
    }

    @Override
    public void onRefresh() {
        swipeRefreshWidget.setRefreshing(false);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {//输入完毕后开始查询
        final String trim = search_edit.getText().toString().trim();
        tvcontent.setVisibility(View.GONE);
        if (!"".equals(trim)) {
            mFriends.clear();
            initData();
        }
    }

    /**
     * 搜索 群成员
     */
    private void dosearch() {
        showProgress(getResources().getString(R.string.now_down));
        final String trim = search_edit.getText().toString().trim();
        if (!"".equals(trim)) {
            mPgService.getGroupMember(groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<SearchUserEntity>() {
                @Override
                public void onNext(SearchUserEntity friendEntivity) {
                    List<ImFriendEntivity> seachtemps = ToolsUtils.gUserRemoval(friendEntivity.getInfo());
//                    List<ImFriendEntivity> seachtemps = friendEntivity.getInfo();
                    List<ImFriendEntivity> seachdatas = new ArrayList<>();
                    if (null != seachtemps && seachtemps.size() > 0) {//有结果
                        for (int k = 0; k < seachtemps.size(); k++) {
                            ImFriendEntivity friends = seachtemps.get(k);
                            //    Log.i("info","群成员名字=="+friends.getName());
                            if (friends.getName().contains(trim)) {
                                seachdatas.add(friends);
                            }
                        }
                        if (seachdatas.size() > 0) {
                            relattive_noresult.setVisibility(View.GONE);
                            mFriends.clear();
                            hideProgress();
                            showListUser(seachdatas);
                        } else {//查询没有结果
                            hideProgress();
                            relattive_noresult.setVisibility(View.VISIBLE);
                            tvcontent.setText(trim);
                            mFriends.clear();
                            showListUser(seachdatas);
                        }
                    } else {
                        hideProgress();
                        relattive_noresult.setVisibility(View.VISIBLE);
                        tvcontent.setText(trim);
                    }
                }

                @Override
                protected void onResultError(ApiException ex) {
                    hideProgress();
                    Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                }
            });

        } else {
            hideProgress();
            relattive_noresult.setVisibility(View.GONE);
            mFriends.clear();
            initData();
        }
    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {//软键盘监听
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN) {//点击了回车键
                dosearch();
                return true;
            }
            return false;
        }
    };
}
